<?php

namespace app\common\logic;

use app\api\service\ApiPayment;
use app\common\library\enum\CodeEnum;
use app\common\library\enum\BalanceCashEnum;
use think\Db;
use think\Log;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;

class BalanceSettlement extends BaseLogic
{
    /**
     * 获取打款列表.
     *
     *
     * @param array  $where
     * @param string $field
     * @param string $order
     * @param int    $paginate
     *
     * @return mixed
     */
    public function getSettlementList($where = [], $field = 'a.*', $order = 'a.update_time desc', $paginate = 15)
    {
        $this->modelBalanceSettlement->alias('a');
        return $this->modelBalanceSettlement->getList($where, $field, $order, $paginate);
    }

    public function saveUserSettlementApplyBatch($filePath = '')
    {
        Db::startTrans();
        try {
            $uid = is_login();
            $spreadsheet = IOFactory::load($filePath); // 载入Excel表格
            $worksheet = $spreadsheet->getActiveSheet();

            $highestRow = $worksheet->getHighestRow(); // 总行数
            if ($highestRow < 2) {
                return [0, 'Excel文件中没有需要处理的数据。'];
            }

            $highestColumn = $worksheet->getHighestColumn(); // 总列数
            $highestColumnIndex = Coordinate::columnIndexFromString($highestColumn);
            if ($highestColumnIndex < 8) {
                return [0, 'Excel文件中数据格式不正确，请使用提供的文件模板。'];
            }

            $allGoodDataList = [];
            for ($row = 2; $row <= $highestRow; ++$row) { // 从第二行开始
                $item = [];
                for ($column = 1; $column <= $highestColumnIndex; ++$column) {
                    $item[] = $worksheet->getCellByColumnAndRow($column, $row)->getValue();
                }

                if (!empty($item[0]) && !empty($item[3]) && !empty($item[4]) && !empty($item[6])) {
                    $index = 0;
                    $allGoodDataList[] = [
                        'user_name' => $item[$index++],
                        'user_idcard' => $item[$index++],
                        'user_phone' => $item[$index++],
                        'bank_account' => $item[$index++],
                        'bank_name' => $item[$index++],
                        'bank_code' => $item[$index++],
                        'amount' => $item[$index++],
                        'remarks' => $item[$index++],
                    ];
                }
            }

            $goodDataCount = sizeof($allGoodDataList);
            if ($goodDataCount <= 0) {
                return [0, 'Excel文件中没有需要处理的数据。'];
            }

            $totalamount = 0;
            foreach ($allGoodDataList as $item) {
                $totalamount = bcadd($totalamount, $item['amount'], 2);
            }

            $user = (new \app\common\model\Balance())->getUserBalance(['uid' => $uid]);
            if (!is_null($user) && $user['enable'] < $totalamount) {
                return [0, '批量结算提交失败, 可用余额不足！'];
            }

            foreach ($allGoodDataList as $item) {
                $settlementList[] = [
                    'uid' => $uid,
                    'no' => create_general_no(),
                    'user_name' => $item['user_name'],
                    'user_idcard' => $item['user_idcard'],
                    'user_phone' => $item['user_phone'],
                    'bank_account' => $item['bank_account'],
                    'bank_name' => $item['bank_name'],
                    'bank_code' => $item['bank_code'],
                    'amount' => $item['amount'],
                    'remarks' => $item['remarks'],
                    'reason' => '',
                    'status' => 1
                ];
            }

            $this->modelBalanceSettlement->saveAll($settlementList);

            if ($this->logicBalanceChange->creatBalanceChange($uid, $totalamount, '批量结算', 'enable', true)) {
                Db::commit();

                action_log('结算', '批量结算申请');

                return [1, '批量结算申请成功, 总共'.$goodDataCount.'条记录等待处理！'];
            } else {
                Db::rollback();

                return [0, '批量结算申请失败, 扣除资金失败！'];
            }

        } catch (\Exception $ex) {
            //记录日志
            Log::error("批量结算申请出现错误:[{$ex->getMessage()}]");
            Db::rollback();

            //抛出错误异常
            return [CodeEnum::ERROR,  config('app_debug') ? $ex->getMessage() : '批量结算申请出现错误'];
        }
    }

    /**
     * 获取订单信息.
     *
     *
     * @param array       $where
     * @param bool|string $field
     *
     * @return mixed
     */
    public function getOrderSettlementInfo($where = [], $field = 'a.*')
    {
        $this->modelBalanceSettlement->alias('a');
        return $this->modelBalanceSettlement->getInfo($where, $field);
    }

    /**
     * 完成结算.
     *
     *
     * @param array $where
     *
     * @return array
     */
    public function dealBalanceSettlement($where = [])
    {
        $order = $this->getOrderSettlementInfo($where);
        Db::startTrans();
        try {
            $this->modelBalanceSettlement->setFieldValue(['id' => $order['id']], 'status', 2);

            Db::commit();

            action_log('完成', '结算申请，单号：'.$order['no']);

            return  ['code' => CodeEnum::SUCCESS, 'msg' => '已经完成'];
        } catch (\Exception $ex) {
            Log::error('完成结算申请出现错误 : '.$ex->getMessage());
            Db::rollback();

            return ['code' => CodeEnum::ERROR, 'msg' => config('app_debug') ? $ex->getMessage() : '完成结算异常'];
        }
    }

    /**
     * 退回结算.
     *
     *
     * @param array $where
     *
     * @return array
     */
    public function rebutBalanceSettlement($where = [], $reason)
    {
        $order = $this->getOrderSettlementInfo($where);

        if (1 != $order['status']) {
            return ['code' => CodeEnum::SUCCESS, 'msg' => '已经处理过了'];
        }

        Db::startTrans();
        try {
            $this->modelBalanceSettlement->setFieldValue(['id' => $order['id']], 'status', 3);
            $this->modelBalanceSettlement->setFieldValue(['id' => $order['id']], 'reason', $reason);

            $this->logicBalanceChange->creatBalanceChange($order['uid'], $order['amount'], '结算退回', 'enable', false);

            Db::commit();

            action_log('退回', '结算申请，单号：'.$order['no']);

            return  ['code' => CodeEnum::SUCCESS, 'msg' => '已经退回'];
        } catch (\Exception $ex) {
            Log::error('退回结算申请出现错误 : '.$ex->getMessage());
            Db::rollback();

            return ['code' => CodeEnum::ERROR, 'msg' => config('app_debug') ? $ex->getMessage() : '退回结算异常'];
        }
    }
}
